<script lang="ts" setup>
import { ElMessage, ElDialog, ElButton } from 'element-plus'
import usePostStore from '@/store/post/index.js'
import router from '@/router/index.js'
import { AiEditor } from "aieditor"
import "aieditor/dist/style.css"
import { onUnmounted ,onMounted, reactive, ref ,nextTick,computed  } from 'vue'
import useLoginStore from '@/store/user/index.js'
import { CirclePlus,Remove,Plus,Minus,LocationInformation, Location, DArrowRight } from '@element-plus/icons-vue'
import AMapLoader from "@amap/amap-jsapi-loader";
const postStore = usePostStore()
const isEdit = ref(false)
const formData = reactive({
  title: '',
  status: 0,
  content: '',
  delFlag:0
})
const divRef = ref()
let aiEditor = null
const loginStore = useLoginStore()
const postId = router.currentRoute._rawValue.query.id;
const dataList = ref([
  { name: '苏州博物馆', value: [120.63,31.32] },
  { name: '尹山湖', value: [120.69,31.24] },
  { name: '同里古镇', value: [120.72,31.16] },
  { name: '甪直古镇', value: [120.87,31.27] },
])
var map = null
var driving = null
var Amap2 = null
// 初始化页面，加载数据（修改时）
onMounted(async () => {
    console.log('传过来的id是',router.currentRoute._rawValue.query.id)

    if (postId != null) {
        try {
            console.log('我进来了')
            isEdit.value = true;
            console.log('isEdit', isEdit)
            const details = await postStore.getPostDetail(postId);
          console.log('details.data', details.data)
          if (details.data) {
            Object.assign(formData, details.data);
          }
        } catch (error) {
            ElMessage.error("加载帖子详情失败");
        }
    }
    aiEditor = new AiEditor({
      element: divRef.value,
      placeholder: "点击输入帖子详情介绍...",
      onChange: (editor) => {
        formData.content = editor.getHtml()
      },
      image: {
        allowBase64: false,
        defaultSize: 350
      },
    })
  // 如果是编辑模式，设置富文本框的初始内容
  if (isEdit.value && formData.content) {
    aiEditor.setContent(formData.content);
  };
  //地图组件
  AMapLoader.load({
    key: "e49b382408169ef1593182e603b44f6d", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.Scale", "AMap.ToolBar",
      "AMap.InfoWindow",//地图弹窗
      "AMap.PlaceSearch",//地点搜索
      "AMap.Geolocation",//定位到当前位置
      "AMap.Geocoder",//经纬度进行逆地理编码查询
      "AMap.Driving",//驾车导航
      "AMap.Transfer",//公交导航
      "AMap.Walking",//步行导航
      "AMap.Riding",//骑行导航
     ], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
    .then((AMap) => {
      map = new AMap.Map("container", {
        // 设置地图容器id
        resizeEnable: true,
        viewMode: "2D", // 是否为3D地图模式
        zoom: 13, // 初始化地图级别
        center: [116.397428, 39.90923], // 初始化地图中心点位置
      });
      // 实例化DrivingSearch
      driving = new AMap.Driving({
        map: map,
        panel: "panel"
      });
      Amap2 = AMap
    }).catch((e) => {
      console.log(e);
    });
});
onUnmounted(() => {
  map?.destroy();
});
const jump = (value) => {
  // 根据起终点经纬度规划驾车导航路线
  console.log('jump', value);
  let start=[120.6519, 31.3989]
  let end=value
  let tu=[120.87,31.27] //途径点
  driving.search(new Amap2.LngLat(start[0],start[1]), new Amap2.LngLat(end[0], end[1]),{
    waypoints:[new Amap2.LngLat(tu[0], tu[1])]
  }, function (status, result) {
    // result即是对应的驾车导航信息
    console.log(status, result);
    if (status === 'complete') {
      console.log('路线规划成功');
    } else {
      console.log('路线规划失败：' + result.info);
    }
  });
}
// 提交表单
const submitForm = async () => {
      if (postId != null) {
          console.log('开始修改了')
          // 修改帖子
          const res = await postStore.updatePosts(formData);
          console.log('修改结果', res);
          if (res.code !== 1) {
            ElMessage.error(res.msg);
          }else {
            router.push("/main/system/post");
            ElMessage.success("修改成功");
          }
      } else {
          // 新增帖子
        const res =  await postStore.addpost(formData);
        if (res.code !== 1) {
          ElMessage.error(res.msg);
        }else {
          console.log('我想要添加成功的弹窗')
          router.push("/main/system/post");
          ElMessage.success("添加成功");
        }
      }
};
// 添加表单校验规则
const formRules = {
  title: [
    { required: true, message: '请输入帖子名称', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入帖子介绍', trigger: 'blur' }
  ]
};
const form = reactive({
  startDescription: "",
});
// 点击出发点描述时显示输入框并聚焦
const handleClickStartDescription = async () => {
  showStartInput.value = true;
  await nextTick(); // 等待 DOM 更新
  startInput.value.focus(); // 聚焦输入框
};
const steps = ref([]);
const showDialog = ref(false);
const newStep = reactive({
  title: "",
  description: "",
  isEnd: false,
});
const showStartInput = ref(false); // 控制出发点输入框的显示
const startInput = ref(null); // 出发点输入框的引用

// 计算属性：判断是否已经存在结束点
const hasEndPoint = computed(() => {
  return steps.value.some((step) => step.isEnd);
});

// 添加步骤
const addStep = () => {
  if (newStep.isEnd) {
    steps.value.push({
      title: "结束点",
      description: newStep.description,
      isEnd: true,
    });
  } else {
    steps.value.push({ ...newStep });
  }
  Object.assign(newStep, { title: "", description: "", isEnd: false });
  showDialog.value = false;
};

// 删除步骤
const removeStep = (index) => {
  steps.value.splice(index, 1);
};

// 当鼠标进入出发点描述区域时，显示输入框并聚焦
const handleMouseEnterStart = async () => {
  showStartInput.value = true;
  await nextTick(); // 等待 DOM 更新
  startInput.value.focus(); // 聚焦输入框
};
</script>

<template>
  <component :is="'script'" type="text/javascript">
    <!-- 使用明文设置安全密钥（不安全），https://lbs.amap.com/api/javascript-api-v2/guide/abc/jscode  -->
    window._AMapSecurityConfig = {securityJsCode: '013be8035e064500a85681a7a0a5edf9'}
  </component>
  <div class="add-container">
    <h2 class="title">{{ isEdit ? '修改路线信息' : '新增路线' }}</h2>
    <el-alert
      v-if="isEdit"
      title="当前为修改操作，请确认信息后提交"
      type="info"
      show-icon
      class="mb-4"
    />
    <el-form :model="formData" :rules="formRules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="路线名称" prop="title">
            <el-input v-model="formData.title" placeholder="请输入路线名称"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="路线介绍" prop="title">
            <el-input v-model="formData.title"
                      :rows="2"
                      type="textarea" placeholder="请输入路线就简单介绍"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="行程天数" prop="title">
            <el-input v-model="formData.title" placeholder="请输入行程天数"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="预算金额" prop="title">
            <el-input v-model="formData.title" placeholder="请输入行程预算金额"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="行程路线" prop="line">
            <el-steps :active="steps.length + 1" align-center>
              <!-- 固定出发步骤 -->
              <el-step title="出发点" :icon="Location" :description="form.startDescription">
                <template #title>
                  <div class="start-point-container">
                    <el-input
                      v-model="form.startDescription"
                      placeholder="请输入出发描述"
                      v-if="showStartInput"
                      @blur="showStartInput = false"
                      ref="startInput"
                    />
                      <span
                      v-else
                      @click="handleClickStartDescription"
                      class="start-description"
                    >
                      {{ form.startDescription || "请输入出发描述" }}
                    </span>
                  </div>
                </template>
              </el-step>

              <!-- 动态步骤区域 -->
              <div v-for="(step, index) in steps" :key="index" class="step-container">
                <!-- 删除按钮 -->
                <div class="delete-btn-container">
                  <el-button
                    :icon="Remove"
                    circle
                    @click="removeStep(index)"
                    class="delete-btn"
                  ></el-button>
                </div>

                <!-- 动态步骤 -->
                <el-step
                  :title="step.isEnd ? '结束点' : step.title"
                  :icon="step.isEnd ? LocationInformation : DArrowRight"
                  :description="step.description"
                >
<!--                  <template #title>
                    <el-input
                      v-model="step.title"
                      :placeholder="step.isEnd ? '结束点' : '请输入步骤标题'"
                      :disabled="step.isEnd"
                    />
                  </template>
                  <template #description>
                    <el-input v-model="step.description" placeholder="请输入步骤描述" />
                  </template>-->
                </el-step>
              </div>

              <!-- 添加按钮（仅在未设置结束点时显示） -->
              <el-button
                v-if="!hasEndPoint"
                :icon="CirclePlus"
                circle
                @click="showDialog = true"
                class="add-btn"
              ></el-button>
            </el-steps>

            <!-- 添加步骤对话框 -->
            <el-dialog v-model="showDialog" title="添加步骤" width="30%">
              <el-form :model="newStep">
                <el-form-item label="步骤标题">
                  <el-input v-model="newStep.title" placeholder="请输入标题" />
                </el-form-item>
                <el-form-item label="步骤描述">
                  <el-input v-model="newStep.description" placeholder="请输入描述" />
                </el-form-item>
                <el-form-item label="是否为终点">
                  <el-switch v-model="newStep.isEnd" />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="showDialog = false">取消</el-button>
                <el-button type="primary" @click="addStep">确认</el-button>
              </template>
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
<!--      <div id="container"></div>
      <div style="position: absolute; top: 20px; left: 20px">
        &lt;!&ndash; 用来触发输入提示插件的容器 &ndash;&gt;
        <input type="text" id="keyword" style="width: 300px; height: 32px; padding-left: 10px" placeholder="请输入地址" />
      </div>-->
      <div class="about">
        <div class="content" id="container"></div>
        <div id="panel"></div>
        <div class="btnbox">
          <div class="btn" @click="jump(item.value)" v-for="item in dataList" :key="item.name">{{ item.name }}</div>
        </div>

      </div>
<!--      <el-form-item label="帖子介绍" prop="content">
        <div ref="divRef" style="height: 400px; border: 1px solid #dcdfe6; border-radius: 4px;"/>
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="router.back()">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="less">
@color1: blue;

.content {
  width: 100vw;
  height: 600px;
  background-color: @color1;

}

.btnbox {
  display: flex;
  width: 500px;
  justify-content: space-between;
  margin-top: 20px;
  margin-left: 20px;
}

.btn {
  width: 100px;
  height: 50px;
  line-height: 50px;
  background-color: rgb(235, 193, 8);
  text-align: center;
  border-radius: 10px;
  cursor: pointer;
}
#panel{
  width: 400px;
  height: 800px;
  overflow-x: auto;
  position: fixed;
  right: 20px;
  top: 20px;
  // background-color: rgb(255, 255, 255)
}
#container {
  width: 100%;
  height: 800px;
}
.step-container {
  position: relative;
  display: flex;
  align-items: center;
}

.delete-btn-container {
  position: absolute;
  top: -30px; /* 将删除按钮移动到步骤条的正上方 */
  left: 50%;
  transform: translateX(-50%);
  z-index: 1;
}

.delete-btn {
  background-color: #fff;
  border: 1px solid #dcdfe6;
}

.start-point-container {
  position: relative;
  display: inline-block;
}

.start-description {
  cursor: pointer;
  padding: 5px;
  border: 1px solid transparent;
  border-radius: 4px;
}

.start-description:hover {
  border-color: #dcdfe6;
}

.add-btn {
  margin-left: 20px;
}
.add-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;

  .el-form {
    max-width: 1000px;
    margin: 0 auto;
  }

  :deep(.el-upload-list) {
    width: 100%;
  }

  :deep(.el-upload) {
    width: 100%;
    .el-button {
      width: 100%;
    }
  }

  .el-upload__tip {
    color: #909399;
    font-size: 12px;
    margin-top: 4px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.title {
   text-align: center; /* 居中显示 */
   font-size: 24px; /* 设置字体大小 */
   font-weight: bold; /* 加粗字体 */
   color: #409EFF; /* 设置字体颜色 */
   margin-bottom: 20px; /* 设置底部间距 */
   padding: 20px 0; /* 设置上下内边距 */
   background-color: #f5f7fa; /* 设置背景颜色 */
   border-radius: 8px; /* 圆角效果 */
   box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
 }

</style>
